 #include "stdafx.h"

#ifdef WIN32
	#include <winnt.h> 
 
#else
	#include <unistd.h>
	#include <dirent.h>
	#include <sys/types.h> // for opendir(), readdir(), closedir()
	#include <sys/stat.h> // for stat()
	#include <stdio.h>
	#include <stdlib.h>
	#include <string.h>
	#include <stdarg.h> 
    #include "base.h"

	#define PROC_DIRECTORY "/proc/"
	#define CASE_SENSITIVE    1
	#define CASE_INSENSITIVE  0
	#define EXACT_MATCH       1
	#define INEXACT_MATCH     0
#endif






#ifndef WIN32

 
bool base::KillProcessFromName(char* szProcessName)
{ 
	if( szProcessName == NULL ) return false;
	 
#ifdef WIN32
#else
	pid_t pid = GetPIDbyName_Wrapper(szProcessName); 
	if( pid <= 0 ) return false; 
		
	kill(pid, SIGTERM);
	kill(pid, SIGTERM); 
#endif
	return true; 
}

pid_t GetPIDbyName_implements(const char* cchrptr_ProcessName, int intCaseSensitiveness, int intExactMatch)
{
    char chrarry_CommandLinePath[100]  ;
    char chrarry_NameOfProcess[300]  ;
    char* chrptr_StringToCompare = NULL ;
    pid_t pid_ProcessIdentifier = (pid_t) -1 ;
    struct dirent* de_DirEntity = NULL ;
    DIR* dir_proc = NULL ;

    int (*CompareFunction) (const char*, const char*, int) ;

    if (intExactMatch)
        CompareFunction = &base::strcmp_Wrapper;
    else
        CompareFunction = &base::strstr_Wrapper;


    dir_proc = opendir(PROC_DIRECTORY) ;
    if (dir_proc == NULL)
    {
        perror("Couldn't open the " PROC_DIRECTORY " directory") ;
        return (pid_t) -2 ;
    }

    // Loop while not NULL
    while ( (de_DirEntity = readdir(dir_proc)) )
    {
        if (de_DirEntity->d_type == DT_DIR)
        {
            if (base::IsNumeric(de_DirEntity->d_name))
            {
                strcpy(chrarry_CommandLinePath, PROC_DIRECTORY) ;
                strcat(chrarry_CommandLinePath, de_DirEntity->d_name) ;
                strcat(chrarry_CommandLinePath, "/cmdline") ;
                FILE* fd_CmdLineFile = fopen (chrarry_CommandLinePath, "rt") ;  //open the file for reading text
                if (fd_CmdLineFile)
                {
                    fscanf(fd_CmdLineFile, "%s", chrarry_NameOfProcess) ; //read from /proc/<NR>/cmdline
                    fclose(fd_CmdLineFile);  //close the file prior to exiting the routine

                    if (strrchr(chrarry_NameOfProcess, '/'))
                        chrptr_StringToCompare = strrchr(chrarry_NameOfProcess, '/') +1 ;
                    else
                        chrptr_StringToCompare = chrarry_NameOfProcess ;

                    //printf("Process name: %s\n", chrarry_NameOfProcess);
                    //�����ȫ·��������/bin/ls
                    //printf("Pure Process name: %s\n", chrptr_StringToCompare );
                    //����Ǵ�������������ls

                    //������ԱȽ�ȫ·����������Ϊchrarry_NameOfProcess����
                    if ( CompareFunction(chrptr_StringToCompare, cchrptr_ProcessName, intCaseSensitiveness) )
                    {
                        pid_ProcessIdentifier = (pid_t) atoi(de_DirEntity->d_name) ;
                        closedir(dir_proc) ;
                        return pid_ProcessIdentifier ;
                    }
                }
            }
        }
    }
    closedir(dir_proc) ;
    return pid_ProcessIdentifier ;
}

    //��ʵ��  If -1 = not found, if -2 = proc fs access error
pid_t base::GetPIDbyName_Wrapper(const char* cchrptr_ProcessName)
{
	return GetPIDbyName_implements(cchrptr_ProcessName, 0,0);//��Сд������
}
 

size_t base::get_executable_path( char* processdir,char* processname, size_t len)
{
        char* path_end;
        if(readlink("/proc/self/exe", processdir,len) <=0)
                return -1;
        path_end = strrchr(processdir,  '/');
        if(path_end == NULL)
                return -1;
        ++path_end;
        strcpy(processname, path_end);
        *path_end = '\0';
        return (size_t)(path_end - processdir);
}

bool base::getPathNamebyPid(pid_t pid,char *name)
 {
     FILE *fptr;
     bool bret = false;
     char cmd[255] = {'\0'};
     sprintf(cmd,"readlink /proc/%d/exe",pid);
     if((fptr = popen(cmd,"r")) != NULL)
     {
         if(fgets(name,255,fptr) != NULL)
         {
             base::my_printf("the path name is %s.\n",name);
             bret = true;
         }

    }

    pclose(fptr);

    return bret;

}
 
bool find_pid(char * fifoPathName, char * chrCurPidName)
{ 
	if( fifoPathName == NULL || chrCurPidName == NULL ) return false;
	
	int cur_pid = getpid();
	
	FILE *fp;

	if( (fp=fopen( fifoPathName,"r+" ))==NULL ){ 
		base::my_printf("open %s error \n", fifoPathName);
		return false;
	} 
	
	char chrTag[512];
	memset(chrTag, 0, 512);
		
	bool is_run = false;
	while( !feof(fp) && fgets( chrTag, 512, fp )!=NULL )
	{ 
		char curPID[32];
		memset(curPID, 0, 32);
		sprintf(curPID, "%d", cur_pid);
		
		if( strstr(chrTag, curPID) )
			continue;
		 
		if( strstr(chrTag, "grep") )
			continue;
		
		if( strstr(chrTag, chrCurPidName) ) {
			is_run = true;
			break;
		}				
		 
		
		memset(chrTag, 0, 512);
	} 
	fclose( fp );

	return is_run; 

}
//arm
bool base::is_existed_pid(char * chrCurPidName)
{	
	int rtn;
	pid_t pid;
	struct stat buf;
	int result; 
	
	if( chrCurPidName == NULL ) return false; 
	 
	char fifoPathName[256];
	sprintf( fifoPathName,"checklog/%s.txt", chrCurPidName );
	
	char ps_buf[128];
	memset(ps_buf, 0, 128);
	
	sprintf(ps_buf, "ps -A|grep %s>%s", chrCurPidName, fifoPathName);

    system(ps_buf);
	 
	if( find_pid(fifoPathName, chrCurPidName) )
	{
 		base::my_printf("ps check:  %s is existed\n", chrCurPidName);
		return true;
	}	
	else {
		base::my_printf("ps check:  %s is not existed \n", chrCurPidName);
		return false;
	}	 
}

#endif